import jieba  # 中文分词器
from matplotlib import pylab as plt  # 绘图库
from wordcloud import WordCloud  # 词云库
import numpy as np
from PIL import Image  # 图像处理
from pymysql import *
import json


# 构建数据连接 第一个参数 是数据库字段 2 模型图片 3,生成新的图片
def get_img(field, targetImageSrc, resImageSrc):
    # con = connect(host= 'localhost', user= 'root', password= '12345', database='ByCarDatas', port='3306',
    #               charset='utf8mb4')
    con = connect(host='localhost', user='root', password='12345', database='ByCarDatas', port=3306, charset='utf8mb4')
    cusor = con.cursor()  # 构建游标
    sql = f"select {field} from carinfo"
    # 执行读取
    cusor.execute(sql)
    data = cusor.fetchall()
    text = ''
    for i in data:
        if i[0] != '':
            tagArr = i
            for j in tagArr:
                text += j
    cusor.close()
    con.close()
    data_cut = jieba.cut(text, cut_all=False)
    string = ''.join(data_cut)

    # 绘制图片
    img = Image.open(targetImageSrc)
    img_arr = np.array(img)
    wc = WordCloud(
        font_path='simkai.ttf',
        mask=img_arr,
        background_color='#04122c'
    )
    wc.generate_from_text(string)
    # 绘制图片
    fig = plt.figure(1)
    plt.imshow(wc)
    plt.axis('off')
    # 保存并去除白边 bbox_inches='tight',pad_inches=-0.1
    plt.savefig(resImageSrc, dpi=800, bbox_inches='tight', pad_inches=-0.1)


get_img('manufacturer', 'D:/学校实训课程/周师实训课程/周师网工实训/资料/katie2.jpg',
        'D:/学校实训课程/周师实训课程/周师网工实训/资料/katie_cloud.jpg')
